package com.surelution.projects.crm

import java.text.SimpleDateFormat

class CardListController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
	def htmlTableParserService
	
    def index = {
        redirect(action: "list", params: params)
    }

    def list = {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
		def sdf = new SimpleDateFormat('yyyy-MM-dd')
		def dateFrom = params.dateFrom? sdf.parse(params.dateFrom):null
		def dateTo = params.dateTo? sdf.parse(params.dateTo):null
		def station = params['station.id']?OwnStation.get(params['station.id']):null
		def result = CardList.createCriteria().list ([max:params.max, offset:params.offset]){
			if(station){
				eq("station",station)
			}
			if(dateFrom) {
				ge("assignTime", dateFrom)
			}
			if(dateTo) {
				le("assignTime", dateTo)
			}
			order("assignTime","desc")
		}
        [cardListInstanceList: result, cardListInstanceTotal: result.totalCount]
    }
	
	def ImportExcelService
	def springSecurityService
	def cardImport = {
		def file = params.cardFile
		int lineNum = 0
		def fileName = file.originalFilename
		ImportExcel excel = ImportExcelService.storeFile(file.inputStream,fileName)
		excel.uploader = springSecurityService.principal.username
		excel.type = "加油卡开卡明细"
		
		BufferedReader br = new BufferedReader(new InputStreamReader(file.inputStream, "utf8"))
		def rows = htmlTableParserService.parse(br)
		rows.each {row->
			println row
			if(lineNum > 1) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
				Date assignTime = new Date()
				assignTime = sdf.parse(row[3])
				if(row.size() > 5) {
					CardList cardList = new CardList("raskNo":row[0],"cardNo":row[1],"thing":row[2],"saleUserNo":row[4],)
					if (OwnStation.findByName(row[5])){
						cardList.station = OwnStation.findByName(row[5])
					}
					else if (StationNameAlias.findByName(row[5])){
							cardList.station = StationNameAlias.findByName(row[5]).station
						}
						else {
							flash.message = "${message(code: 'default.noFoundStationName.message', args:[row[5]])}"
							cardList.station = OwnStation.get(78)
							}
					cardList.assignTime = assignTime
					cardList.save()
					println cardList
					flash.message = "${message(code: 'default.updateFileSuccess.message', args: [message(code: 'cardList.label', default: 'cardList')])}"
				}
			}
			lineNum++
		}
		excel.save()
        redirect(action: "list")
	}

    def create = {
        def cardListInstance = new CardList()
        cardListInstance.properties = params
        return [cardListInstance: cardListInstance]
    }

    def save = {
        def cardListInstance = new CardList(params)
        if (cardListInstance.save(flush: true)) {
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'cardList.label', default: 'CardList'), cardListInstance.id])}"
            redirect(action: "show", id: cardListInstance.id)
        }
        else {
            render(view: "create", model: [cardListInstance: cardListInstance])
        }
    }

    def show = {
        def cardListInstance = CardList.get(params.id)
        if (!cardListInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'cardList.label', default: 'CardList'), params.id])}"
            redirect(action: "list")
        }
        else {
            [cardListInstance: cardListInstance]
        }
    }

    def edit = {
        def cardListInstance = CardList.get(params.id)
        if (!cardListInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'cardList.label', default: 'CardList'), params.id])}"
            redirect(action: "list")
        }
        else {
            return [cardListInstance: cardListInstance]
        }
    }

    def update = {
        def cardListInstance = CardList.get(params.id)
        if (cardListInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (cardListInstance.version > version) {
                    
                    cardListInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'cardList.label', default: 'CardList')] as Object[], "Another user has updated this CardList while you were editing")
                    render(view: "edit", model: [cardListInstance: cardListInstance])
                    return
                }
            }
            cardListInstance.properties = params
            if (!cardListInstance.hasErrors() && cardListInstance.save(flush: true)) {
                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'cardList.label', default: 'CardList'), cardListInstance.id])}"
                redirect(action: "show", id: cardListInstance.id)
            }
            else {
                render(view: "edit", model: [cardListInstance: cardListInstance])
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'cardList.label', default: 'CardList'), params.id])}"
            redirect(action: "list")
        }
    }

    def delete = {
        def cardListInstance = CardList.get(params.id)
        if (cardListInstance) {
            try {
                cardListInstance.delete(flush: true)
                flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'cardList.label', default: 'CardList'), params.id])}"
                redirect(action: "list")
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'cardList.label', default: 'CardList'), params.id])}"
                redirect(action: "show", id: params.id)
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'cardList.label', default: 'CardList'), params.id])}"
            redirect(action: "list")
        }
    }
}
